package system;

import java.lang.reflect.Method

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpSession

import org.iweb.html.api.AppState
import org.iweb.html.impl.session.AppSession
import org.iweb.html.impl.session.MainManager
import org.iweb.ioc.Bean
import org.iweb.ioc.ServiceLookup
import org.iweb.ui.company.Company
import org.iweb.ui.company.CompanyFactory
import org.iweb.web.filter.Filter
import org.slf4j.Logger
import org.slf4j.LoggerFactory


@Filter(beanName="system.RouteFilter")
@Bean("system.RouteFilter")
public class RouteFilter{
	
	private Logger log=LoggerFactory.getLogger(RouteFilter.class);
	
	public void filter(HttpServletRequest request,HttpServletResponse response){
		HttpSession session=request.getSession();
		
		AppSession appSession=(AppSession) session.getAttribute("APPLICATION");
		
		if(appSession==null){
			appSession=new AppSession();
			appSession.setId(session.getId());
		}
		
		appSession.setAppState(new AppState());
		
		MainManager.setAppSession(appSession);
		
		
		String clientHost = request.getHeader("host");
		
		if(clientHost!=null){
			log.debug("Client HOSTNAME: "+clientHost);
			boolean match=false;
			
			Object company;
			Class companyClass;
			Method method;
			
			for(Company com: CompanyFactory.getInstance().getCompanies().keySet()){
				if(clientHost.matches(com.hostname())){
					log.debug("Client HOSTNAME MATCH: "+com.hostname());
					companyClass=CompanyFactory.getInstance().getCompanies().get(com);//.getApplication().route(request,response,appSession);
					
					company=ServiceLookup.getInstance().get(com.beanName());
					
					try {
						method=companyClass.getMethod(com.routeMethod(),HttpServletRequest.class,HttpServletResponse.class,AppSession.class);
						method.invoke(company, request,response,appSession);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					match=true;
					break;
				}
			}
			
			//No matches, return default
			if(!match){
				//getCompanies().get("localhost(:[0-9]*)").getApplication().route(request,response,appSession);
				response.writer.write(clientHost);
			}
		}
		
		MainManager.clean();
		session.setAttribute("APPLICATION",appSession);
	}
	
}